package org.jeecg.modules.mes.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.jeecg.modules.mes.mapper.MesStatisticsMapper;
import org.jeecg.modules.mes.service.IMesStatisticsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * MES生产统计服务实现类
 * 
 * @author wanke-erp
 * @since 2025-09-15
 */
@Service
@Slf4j
public class MesStatisticsServiceImpl implements IMesStatisticsService {

    @Autowired
    private MesStatisticsMapper mesStatisticsMapper;

    /**
     * 安全获取BigDecimal值
     */
    private BigDecimal getBigDecimalValue(Object value) {
        if (value == null) {
            return BigDecimal.ZERO;
        }
        if (value instanceof BigDecimal) {
            return (BigDecimal) value;
        }
        if (value instanceof Number) {
            return new BigDecimal(value.toString());
        }
        try {
            return new BigDecimal(value.toString());
        } catch (NumberFormatException e) {
            log.warn("无法转换为BigDecimal: {}", value);
            return BigDecimal.ZERO;
        }
    }

    /**
     * 获取默认日期范围
     */
    private Map<String, String> getDefaultDateRange(String startDate, String endDate) {
        Map<String, String> dateRange = new HashMap<>();
        
        if (!StringUtils.hasText(startDate)) {
            startDate = LocalDate.now().minusMonths(1).format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        }
        if (!StringUtils.hasText(endDate)) {
            endDate = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        }
        
        dateRange.put("startDate", startDate);
        dateRange.put("endDate", endDate);
        return dateRange;
    }

    @Override
    public Map<String, Object> getProductionEfficiencyOverview(String startDate, String endDate) {
        Map<String, String> dateRange = getDefaultDateRange(startDate, endDate);
        
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 获取生产计划完成率
            Map<String, Object> planCompletion = mesStatisticsMapper.getPlanCompletionRate(
                dateRange.get("startDate"), dateRange.get("endDate"));
            result.put("planCompletionRate", planCompletion != null ? 
                getBigDecimalValue(planCompletion.get("completion_rate")) : BigDecimal.ZERO);
            
            // 获取任务按时完成率
            Map<String, Object> onTimeCompletion = mesStatisticsMapper.getOnTimeCompletionRate(
                dateRange.get("startDate"), dateRange.get("endDate"));
            result.put("onTimeCompletionRate", onTimeCompletion != null ? 
                getBigDecimalValue(onTimeCompletion.get("on_time_rate")) : BigDecimal.ZERO);
            
            // 获取平均生产周期
            Map<String, Object> avgCycle = mesStatisticsMapper.getAverageProductionCycle(
                dateRange.get("startDate"), dateRange.get("endDate"));
            result.put("averageProductionCycle", avgCycle != null ? 
                getBigDecimalValue(avgCycle.get("avg_cycle_days")) : BigDecimal.ZERO);
            
            // 获取员工生产效率
            Map<String, Object> employeeEfficiency = mesStatisticsMapper.getEmployeeEfficiencyOverview(
                dateRange.get("startDate"), dateRange.get("endDate"));
            result.put("employeeEfficiency", employeeEfficiency != null ? 
                getBigDecimalValue(employeeEfficiency.get("avg_efficiency_rate")) : BigDecimal.ZERO);
            
        } catch (Exception e) {
            log.error("获取生产效率概览统计失败", e);
            // 返回默认值
            result.put("planCompletionRate", BigDecimal.ZERO);
            result.put("onTimeCompletionRate", BigDecimal.ZERO);
            result.put("averageProductionCycle", BigDecimal.ZERO);
            result.put("employeeEfficiency", BigDecimal.ZERO);
        }
        
        return result;
    }

    @Override
    public Map<String, Object> getPlanVsActualData(String startDate, String endDate, String timeType) {
        Map<String, String> dateRange = getDefaultDateRange(startDate, endDate);
        
        Map<String, Object> result = new HashMap<>();
        
        try {
            List<Map<String, Object>> planData = mesStatisticsMapper.getPlanData(
                dateRange.get("startDate"), dateRange.get("endDate"), timeType);
            List<Map<String, Object>> actualData = mesStatisticsMapper.getActualData(
                dateRange.get("startDate"), dateRange.get("endDate"), timeType);
            
            result.put("planData", planData != null ? planData : new ArrayList<>());
            result.put("actualData", actualData != null ? actualData : new ArrayList<>());
            
        } catch (Exception e) {
            log.error("获取生产计划vs实际完成对比数据失败", e);
            result.put("planData", new ArrayList<>());
            result.put("actualData", new ArrayList<>());
        }
        
        return result;
    }

    @Override
    public List<Map<String, Object>> getProductionEfficiencyTrend(String startDate, String endDate, String timeType) {
        Map<String, String> dateRange = getDefaultDateRange(startDate, endDate);
        
        try {
            List<Map<String, Object>> result = mesStatisticsMapper.getProductionEfficiencyTrend(
                dateRange.get("startDate"), dateRange.get("endDate"), timeType);
            return result != null ? result : new ArrayList<>();
        } catch (Exception e) {
            log.error("获取生产效率趋势数据失败", e);
            return new ArrayList<>();
        }
    }

    @Override
    public List<Map<String, Object>> getProcessTimeAnalysis(String startDate, String endDate) {
        Map<String, String> dateRange = getDefaultDateRange(startDate, endDate);
        
        try {
            List<Map<String, Object>> result = mesStatisticsMapper.getProcessTimeAnalysis(
                dateRange.get("startDate"), dateRange.get("endDate"));
            return result != null ? result : new ArrayList<>();
        } catch (Exception e) {
            log.error("获取工序耗时分析数据失败", e);
            return new ArrayList<>();
        }
    }

    @Override
    public List<Map<String, Object>> getTaskStatusDistribution(String startDate, String endDate) {
        Map<String, String> dateRange = getDefaultDateRange(startDate, endDate);
        
        try {
            List<Map<String, Object>> result = mesStatisticsMapper.getTaskStatusDistribution(
                dateRange.get("startDate"), dateRange.get("endDate"));
            return result != null ? result : new ArrayList<>();
        } catch (Exception e) {
            log.error("获取任务状态分布数据失败", e);
            return new ArrayList<>();
        }
    }

    @Override
    public List<Map<String, Object>> getEmployeeEfficiencyRanking(String startDate, String endDate, Integer limit) {
        Map<String, String> dateRange = getDefaultDateRange(startDate, endDate);
        
        if (limit == null || limit <= 0) {
            limit = 10;
        }
        
        try {
            List<Map<String, Object>> result = mesStatisticsMapper.getEmployeeEfficiencyRanking(
                dateRange.get("startDate"), dateRange.get("endDate"), limit);
            return result != null ? result : new ArrayList<>();
        } catch (Exception e) {
            log.error("获取员工效率排行榜失败", e);
            return new ArrayList<>();
        }
    }

    @Override
    public Map<String, Object> getPersonnelEfficiencyOverview(String startDate, String endDate) {
        Map<String, String> dateRange = getDefaultDateRange(startDate, endDate);
        
        try {
            Map<String, Object> result = mesStatisticsMapper.getPersonnelEfficiencyOverview(
                dateRange.get("startDate"), dateRange.get("endDate"));
            return result != null ? result : new HashMap<>();
        } catch (Exception e) {
            log.error("获取人员效率概览统计失败", e);
            return new HashMap<>();
        }
    }

    @Override
    public List<Map<String, Object>> getEmployeeProductionRanking(String startDate, String endDate, Integer limit) {
        Map<String, String> dateRange = getDefaultDateRange(startDate, endDate);
        
        if (limit == null || limit <= 0) {
            limit = 10;
        }
        
        try {
            List<Map<String, Object>> result = mesStatisticsMapper.getEmployeeProductionRanking(
                dateRange.get("startDate"), dateRange.get("endDate"), limit);
            return result != null ? result : new ArrayList<>();
        } catch (Exception e) {
            log.error("获取员工产量排行失败", e);
            return new ArrayList<>();
        }
    }

    @Override
    public List<Map<String, Object>> getWorkHourUtilization(String startDate, String endDate) {
        Map<String, String> dateRange = getDefaultDateRange(startDate, endDate);
        
        try {
            List<Map<String, Object>> result = mesStatisticsMapper.getWorkHourUtilization(
                dateRange.get("startDate"), dateRange.get("endDate"));
            return result != null ? result : new ArrayList<>();
        } catch (Exception e) {
            log.error("获取工时利用率统计失败", e);
            return new ArrayList<>();
        }
    }

    @Override
    public List<Map<String, Object>> getSkillDistribution(String startDate, String endDate) {
        Map<String, String> dateRange = getDefaultDateRange(startDate, endDate);
        
        try {
            List<Map<String, Object>> result = mesStatisticsMapper.getSkillDistribution(
                dateRange.get("startDate"), dateRange.get("endDate"));
            return result != null ? result : new ArrayList<>();
        } catch (Exception e) {
            log.error("获取技能分布统计失败", e);
            return new ArrayList<>();
        }
    }

    @Override
    public List<Map<String, Object>> getTrainingEffectAnalysis(String startDate, String endDate) {
        Map<String, String> dateRange = getDefaultDateRange(startDate, endDate);
        
        try {
            List<Map<String, Object>> result = mesStatisticsMapper.getTrainingEffectAnalysis(
                dateRange.get("startDate"), dateRange.get("endDate"));
            return result != null ? result : new ArrayList<>();
        } catch (Exception e) {
            log.error("获取培训效果分析失败", e);
            return new ArrayList<>();
        }
    }
}
